package com.sys.dao.impl;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.sys.dao.MsgDao;
import com.sys.domain.Msg;
import com.sys.utils.C3P0Utils;

public class MsgDaoImpl implements MsgDao {
	private QueryRunner queryRunner;
	public MsgDaoImpl() {
		queryRunner = new QueryRunner(C3P0Utils.getDataSource());
	}
	
	@Override
	public Boolean insertMsg(String userId, String msg) throws SQLException {
		String sql = "insert into msgs values(?,?,?)";
		SimpleDateFormat dFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String currentDate = dFormat.format(System.currentTimeMillis());
		int row = queryRunner.update(sql, userId, msg, currentDate);
		return row > 0?true:false;
	}

	@Override
	public List<Msg> getAllMsg() throws SQLException {
		String sql = "select user as userId, msg as msg, time as time from msgs";
		List<Msg> msgs = queryRunner.query(sql, new BeanListHandler<Msg>(Msg.class));
		Collections.sort(msgs);
		return msgs;
	}

	@Override
	public Boolean deleteMsg(String userId, String msg) throws SQLException {
		String sql = "delete from msgs where user = ? and msg = ?";
		int row = queryRunner.update(sql, userId, msg);
		return row>0?true:false;
	}
}